using System;
using System.Threading.Tasks;
using Windows.Storage;
using GoChat_for_Windows.Models;
using Newtonsoft.Json;

namespace GoChat_for_Windows.Services
{
    public class LocalStorageService : ILocalStorageService
    {
        private const string UserKey = "CurrentUser";
        private const string TokenKey = "AuthToken";
        private readonly ApplicationDataContainer _localSettings;

        public LocalStorageService()
        {
            _localSettings = ApplicationData.Current.LocalSettings;
        }

        public Task SaveUserAsync(User user)
        {
            if (user == null)
                throw new ArgumentNullException(nameof(user));

            var userJson = JsonConvert.SerializeObject(user);
            _localSettings.Values[UserKey] = userJson;
            return Task.CompletedTask;
        }

        public Task<User?> GetUserAsync()
        {
            if (_localSettings.Values.TryGetValue(UserKey, out object? userJson) && userJson != null)
            {
                try
                {
                    var user = JsonConvert.DeserializeObject<User>(userJson.ToString()!);
                    return Task.FromResult(user);
                }
                catch
                {
                    return Task.FromResult<User?>(null);
                }
            }
            return Task.FromResult<User?>(null);
        }

        public Task ClearUserAsync()
        {
            _localSettings.Values.Remove(UserKey);
            return Task.CompletedTask;
        }

        public Task SaveTokenAsync(string token)
        {
            if (string.IsNullOrEmpty(token))
                throw new ArgumentNullException(nameof(token));

            _localSettings.Values[TokenKey] = token;
            return Task.CompletedTask;
        }

        public Task<string?> GetTokenAsync()
        {
            return Task.FromResult(_localSettings.Values[TokenKey]?.ToString());
        }

        public Task ClearTokenAsync()
        {
            _localSettings.Values.Remove(TokenKey);
            return Task.CompletedTask;
        }
    }
} 